﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using System.Windows.Forms;
using Keyrox.Shell;
using System.Drawing;
using System.Reflection;
using Microsoft.Win32;
using System.Diagnostics;

namespace SVNClean.Shell {
    [ComVisible(true), Guid("0056DA96-FFD6-4180-BAB2-8C9B6F552B2D")]
    public class SvnCleanerMenu : BaseContextMenu {

        /// <summary>
        /// Menu Item Call Back.
        /// </summary>
        delegate void MenuItemCallBack();

        #region "[rgn] Menu Item Builder "
        [ComRegisterFunction]
        public static void RegisterFunction(Type t) {
            RegisterContextMenu.Register("Directory", t.GUID);
            RegisterContextMenu.Register("Drive", t.GUID);
            //RegisterContextMenu.Register("*", t.GUID);
        }

        [ComUnregisterFunction]
        public static void UnregisterFunction(Type t) {
            RegisterContextMenu.Unregister("Directory", t.GUID);
            RegisterContextMenu.Unregister("Drive", t.GUID);
            //RegisterContextMenu.Unregister("*", t.GUID);
        }

        public override void AssembleMenu() {
            System.Drawing.Bitmap bmp001 = new System.Drawing.Bitmap(Assembly.GetExecutingAssembly().GetManifestResourceStream("SVNClean.Shell.shellico1.bmp"));
            System.Drawing.Bitmap bmp002 = new System.Drawing.Bitmap(Assembly.GetExecutingAssembly().GetManifestResourceStream("SVNClean.Shell.shellico10.bmp"));
            System.Drawing.Bitmap bmp003 = new System.Drawing.Bitmap(Assembly.GetExecutingAssembly().GetManifestResourceStream("SVNClean.Shell.shellico11.bmp"));

            MenuItems menuRoot = new MenuItems("SVN Cleaner", 0, false, bmp001, false);
            MenuItems menuClear = new MenuItems("Clear this Directory", 1, false, bmp002, false);
            MenuItems menuBackup = new MenuItems("Backup and Clear", 2, false, bmp003, false);
            MenuItems menuSep = new MenuItems("Separator", 3, true);
            MenuItems menuCount = new MenuItems("Count SVN References", 4, false, bmp003, false);

            menuClear.Click += new MenuItems.MenuClickHandler(menuClear_Click);
            menuBackup.Click += new MenuItems.MenuClickHandler(menuBackup_Click);
            menuCount.Click += new MenuItems.MenuClickHandler(menuCount_Click);

            InsertMenu(menuRoot);
            AddMenu(menuRoot, menuClear);
            AddMenu(menuRoot, menuBackup);
            AddMenu(menuRoot, menuSep);
            AddMenu(menuRoot, menuCount);
        }
        #endregion

        #region "[rgn] Menu Item Handler "
        private void menuClear_Click(object path) {
            if (path != null && !string.IsNullOrEmpty(path.ToString())) {
                LaunchSVNCleaner(string.Format("clear {0}", path.ToString()));
            }
        }
        private void menuBackup_Click(object path) {
            if (path != null && !string.IsNullOrEmpty(path.ToString())) {
                LaunchSVNCleaner(string.Format("clearbackup {0}", path.ToString()));
            }
        }
        private void menuCount_Click(object path) {
            if (path != null && !string.IsNullOrEmpty(path.ToString())) {
                LaunchSVNCleaner(string.Format("count {0}", path.ToString()));
            }
        }
        private void LaunchSVNCleaner(string args) {
            if (IsSVNInstalled()) {
                new MenuItemCallBack(delegate() {

                    var si = new ProcessStartInfo();
                    si.FileName = GetSVNCleanerPath();
                    si.Arguments = args;
                    si.UseShellExecute = true;
                    Process.Start(si);

                }).BeginInvoke(null, null);
            }
            else {
                UnregisterFunction(this.GetType());
                MessageBox.Show("SVNCleaner not found!\n\nContext items was removed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        /// <summary>
        /// Gets the SVN cleaner path.
        /// </summary>
        /// <returns></returns>
        private static string GetSVNCleanerPath() {
            using (var registry = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, Environment.MachineName)) {
                var key = registry.CreateSubKey(string.Concat(@"SOFTWARE\KEYROX\SVNCLEANER\"), RegistryKeyPermissionCheck.ReadWriteSubTree);
                var path = key.GetValue("PATH");
                return path != null ? path.ToString() : string.Empty;
            }
        }

        /// <summary>
        /// Determines whether [is SVN installed].
        /// </summary>
        /// <returns>
        /// 	<c>true</c> if [is SVN installed]; otherwise, <c>false</c>.
        /// </returns>
        private static bool IsSVNInstalled() {
            return new FileInfo(GetSVNCleanerPath()).Exists;
        }
    }
}
